package com.smarthealthring.mm.net;

import com.smarthealthring.mm.App;
import com.smarthealthring.mm.BuildConfig;
import com.smarthealthring.mm.api.ApiResponse;
import com.smarthealthring.mm.api.ResultJsonDeser;
import com.smarthealthring.mm.utils.SystemUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * 构建Retrofit
 * <p>
 * Created by hewei26 on 2016/9/28.
 */

public class NetworkManager {
    private static final int COMMON_HEAD = 1;
    private static final int RONGCLOUD_HEAD = 2;

    private static Retrofit commonClient = null;
    private static Retrofit wechatClient = null;

    private static String lastUrl;

    public static final String PORT_HOST = "http://118.31.78.173:8080/rings-web/";
    public static final String WECHAT_HOST = "https://api.weixin.qq.com/sns/oauth2/";

    private NetworkManager() {
    }

    /**
     * 普通接口
     *
     * @return
     */
    public static Retrofit getCommonClient() {
        if (commonClient == null) {
            Gson gson = new GsonBuilder()
                    .registerTypeHierarchyAdapter(ApiResponse.class, new ResultJsonDeser())
                    .create();
            commonClient = new Retrofit.Builder()
                    .baseUrl(PORT_HOST)
                    .client(getHttpClient(COMMON_HEAD))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return commonClient;
    }

    public static Retrofit getWechatClient() {
        if (wechatClient == null) {
            Gson gson = new GsonBuilder()
                    .registerTypeHierarchyAdapter(ApiResponse.class, new ResultJsonDeser())
                    .create();
            wechatClient = new Retrofit.Builder()
                    .baseUrl(WECHAT_HOST)
                    .client(getHttpClient(COMMON_HEAD))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return wechatClient;
    }




    public static OkHttpClient getHttpClient(final int headType) {
        //只在debug下输出日志的拦截器
        Interceptor okhttpLogInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                //add headers
                request = addHeaders(headType, request);

                if (BuildConfig.DEBUG) {
                    long t1 = System.nanoTime();
                    Response response = chain.proceed(request);
                    long t2 = System.nanoTime();

                    double time = (t2 - t1) / 1e6d;

                    MediaType contentType = response.body().contentType();
                    String bodyString = response.body().string();

                    String msg = request.method() + "\nurl->" + request.url()
                            + "\ntime->" + time
                            + "ms\nheaders->" + request.headers()
                            + "\nresponse code->" + response.code()
                            + "\nresponse headers->" + response.headers()
                            + "\nbody->" + bodyString;

                    if (request.method().equals("GET")) {
                        Logger.i(msg);
                    } else if (request.method().equals("POST")) {
                        Request copyRequest = request.newBuilder().build();
//                            if (copyRequest.body() instanceof FormBody) {
                            Buffer buffer = new Buffer();
                            copyRequest.body().writeTo(buffer);
                            Logger.i("request params:" + buffer.readUtf8());
//                        }
                        Logger.i(msg);
                    } else if (request.method().equals("PUT")) {
                        Logger.i(msg);
                    } else if (request.method().equals("DELETE")) {
                        Logger.i(msg);
                    }
                    ResponseBody body = ResponseBody.create(contentType, bodyString);
                    return response.newBuilder().body(body).build();
                } else {
                    return chain.proceed(request);
                }
            }
        };

        //设置缓存拦截器
        File httpCacheDirectory = new File(App.getInstance().getCacheDir(), "responses"); //缓存位置大小
        Cache cache = new Cache(httpCacheDirectory, 50 * 1024 * 1024);

        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!SystemUtil.isNetworkConnected()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }

                Response response = chain.proceed(request);

                if (SystemUtil.isNetworkConnected()) {
                    int maxAge = 0 * 60; // 有网络时 设置缓存超时时间0个小时
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    int maxStale = 0; // 无网络时，设置超时为3秒
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };

        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(okhttpLogInterceptor)
//                .addInterceptor(cacheInterceptor)
                .cache(cache)
                .build();
    }

    /**
     * 添加请求头
     *
     * @param type    区分不同的API
     * @param request
     * @return
     */
    private static Request addHeaders(int type, Request request) {
        Request.Builder requestBuild = request.newBuilder();
        return requestBuild.build();
    }
}

